﻿using Abp.Configuration.Startup;
using Abp.Localization.Dictionaries.Xml;
using Abp.Localization.Dictionaries;
using Abp.Modules;
using System;
using System.Reflection;
using Abp.Reflection.Extensions;
using Abp.Localization.Sources;

namespace AbpProjectTemplate.Localization
{
    public static class LocalizationExtensions
    {
        /// <summary>
        /// 获取枚举对应的语言key，用于配置多语言的显示名称
        /// </summary>
        public static string GetLanguateKey(this Enum obj)
        {
            var type = obj.GetType().GetField(obj.ToString());
            var attr = type.GetCustomAttribute<LanguateKeyAttribute>();
            if (attr != null)
                return attr.Key;
            return type.Name;
        }
        /// <summary>
        /// 添加xml配置（XmlEmbeddedFile）,文件需要嵌入资源，配置文件命名空间为：
        /// module的命名空间.Localization.SourceFiles
        /// </summary>
        public static void AddXmlSource(
            this ILocalizationConfiguration configuration,
            AbpModule module,
            string sourceName)
        {
            var assembly = module.GetType().GetAssembly();
            configuration.Sources.Add(
                new DictionaryBasedLocalizationSource(sourceName,
                    new XmlEmbeddedFileLocalizationDictionaryProvider(
                        assembly,
                        $"{module.GetType().Namespace}.Localization.SourceFiles"
                    )
                )
            );
        }

        /// <summary>
        /// 扩展xml（XmlEmbeddedFile）,文件需要嵌入资源，配置文件命名空间为：
        /// module的命名空间.Localization.Extensions
        /// </summary>
        public static void ExtendXmlSource(
            this ILocalizationConfiguration configuration,
            AbpModule module,
            string sourceName)
        {
            var assembly = module.GetType().GetAssembly();
            configuration.Sources.Extensions.Add(
               new LocalizationSourceExtensionInfo(sourceName,
                   new XmlEmbeddedFileLocalizationDictionaryProvider(
                       assembly,
                       $"{module.GetType().Namespace}.Localization.Extensions"
                   )
               )
           );
        }
    }
}

